home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1593 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: news.iag.net!news
  2. From: jatmon@iag.net (John R Buchan)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Q: realloc->free?
  5. Date: 15 Jan 1996 15:52:50 GMT
  6. Organization: Internet Access Group, Orlando, Florida
  7. Message-ID: <4ddt8i$1a1@news.iag.net>
  8. References: <4daa2e$oh5@axe.netdoor.com>
  9. NNTP-Posting-Host: pm1-orl26.iag.net
  10. X-Newsreader: WinVN 0.99.7
  11.  
  12. In article <4daa2e$oh5@axe.netdoor.com>, esargent@netdoor.com says...
  13. >
  14. >        This is probably a dumb question, but I can't find any specific or
  15. >exact information about this.  Given this:
  16. >
  17. >char *a, *b;
  18. >
  19. >a = malloc(10);
  20. >...
  21. >/*
  22. >        later we need to increase the size
  23. >*/
  24. >...
  25. >b = realloc(a, 100);
  26.  
  27. >
  28. >        Now let's say realloc had to move the data so a != b.  Does realloc
  29. >free the memory previously pointed to by a or should it be explicitly
  30. >freed if realloc returns a new location?  I checked the FAQ, but there
  31. >was nothing specific about realloc.  Thanks for any information.
  32.  
  33. If realloc succeeds, it will take care of a (it may or may not free it, 
  34. depending on whether it actually allocated an entirely new block or was
  35. able to add on to the existing block).  Do not free it yourself!
  36.  
  37. If realloc fails, then a is still a valid pointer to the original data and
  38. you will need to handle it.  
  39.  
  40.  
  41. In a simple program, you might add something like this to your code:
  42.  
  43. if( b == NULL) /* realloc failed */
  44.   {
  45.   /* a is still valid. */
  46.   fprintf( stderr, "Insufficient memeory  to continue.\n");
  47.   free(a);
  48.   return;
  49.   }
  50. else
  51.   a = b;
  52.  
  53.  
  54.  
  55. -- 
  56. John R Buchan           -:|:-     Looking for that elusive FAQ?  ftp to:
  57. jatmon@mail.iag.net     -:|:-     rtfm.mit.edu /pub/usenet-by-group/....
  58.  
  59.